<?php

class Edm_Controller_Plugin_AclManager extends Zend_Controller_Plugin_Abstract {

    //default user role if not logged or (or invalid role found)
    private $_defaultRole = 'guest';
    private $_adminRole = 'administrator';
    private $_authController = array(
        'module' => 'admin',
        'controller' => 'index',
        'action' => 'login');

    /**
     * AclManager
     */
    public function __construct() {
        $this->auth = Zend_Auth::getInstance();
        $this->acl = new Zend_Acl();

        $this->acl->addRole(new Zend_Acl_Role($this->_defaultRole));
        $this->acl->addRole(new Zend_Acl_Role($this->_adminRole));

        //资源
        $resource = new Zend_Config_Ini(PROJECT_ROOT . '/library/Edm/Config/Resource.ini', null);
        foreach ($resource->toArray() as $key => $arr) {
            $this->acl->add(new Zend_Acl_Resource($key));
            foreach ($arr as $value) {
                $this->acl->add(new Zend_Acl_Resource($value), $key);
            }
        }

        //游客权限，可以访问的资源
        $this->acl->allow('guest', 'front:index');
        $this->acl->allow('guest', 'front:users');
        $this->acl->allow('guest', 'front:message');
        $this->acl->allow('guest', 'admin:index', array('login'));

        //管理员拥有所以权限
        $this->acl->allow($this->_adminRole);
    }

    /* 指定用户可访问的资源 */

    public function preDispatch(Zend_Controller_Request_Abstract $request) {
        $identity = $this->auth->getIdentity();
        if ($this->auth->hasIdentity() && isset($identity->role)) {
            $role = $identity->role;
        } else {
            $role = $this->_defaultRole;
        }

        $module = $request->module;
        $controller = $request->controller;
        $action = $request->action;
        $resource = "$module:$controller";

        if (!$this->acl->has($resource)) {
            $resource = null;
        }

        if (!$this->acl->isAllowed($role, $resource, $action)) {
            $request->setModuleName($this->_authController['module']);
            $request->setControllerName($this->_authController['controller']);
            $request->setActionName($this->_authController['action']);
        }
    }

}